/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */

/**
 * 要先保证提交一个正确结果
 * @param {*} root
 * @param {*} voyage
 */
/**
 * @param {TreeNode} root
 * @param {number[]} voyage
 * @return {number[]}
 */
var flipMatchVoyage = function (root, voyage) {
  const flipList = [];
  let i = 0;
  const swap = (node) => {
    const p = node.left;
    flipList.push(node.val);
    node.left = node.right;
    node.right = p;
  };
  const preOrder = (node) => {
    if (!node) {
      return true;
    }
    if (node.val !== voyage[i]) {
      return false;
    }
    i++;
    //! 这里不能直接递归
    if (node.left && node.left.val !== voyage[i]) {
      swap(node);
    }
    return preOrder(node.left) && preOrder(node.right);
  };
  return preOrder(root) ? flipList : [-1];
};
